#include "netpack.h"
#include "network.h"
#include <memory.h>
#include <assert.h>

NetPacket::~NetPacket()
{
    if(_msg)
    {
        destroymessage(_msg);
        _msg=NULL;
    }
}

NetPacket::NetPacket(uint16 id)
    :_recv(false)
{
    _msg=createmessage();
    *(uint16*)_msg->data=id;
    _msg->datalen=sizeof(uint16);
}

NetPacket::NetPacket(NetMessage* msg)
    :_recv(true)
{
    _msg=msg;
}

void* NetPacket::RawData() const
{
    return _msg->data+sizeof(uint16);
}

void NetPacket::SetLength(uint16 len)
{
	if(!_recv)
	{
		if(len+sizeof(uint16)<=sizeof(_msg->data))
			_msg->datalen=len+sizeof(uint16);
	}
}

uint16 NetPacket::GetLength() const
{
    if(_msg->datalen>sizeof(uint16))
        return _msg->datalen-sizeof(uint16);
    return 0;
}

void NetPacket::IncLength(uint16 len)
{
	if(!_recv)
    {
		if(_msg->datalen+len<=sizeof(_msg->data))
			_msg->datalen+=len;
	}
}

uint16 NetPacket::Id() const
{
    return *(uint16*)_msg->data;
}

uint16 NetPacket::MaxSize() const
{
	if(!_recv)
		return sizeof(_msg->data)-sizeof(uint16);
	return GetLength();
}

void NetPacket::AssignData(const NetPacket& pack)
{
	if(!_recv)
    {
		assert(pack._msg->datalen<=sizeof(pack._msg->data));
		_msg->datalen=pack._msg->datalen;
		if(pack._msg->datalen<=sizeof(_msg->data))
			memcpy(_msg->data,pack._msg->data,pack._msg->datalen);
	}
}

NetMessage* NetPacket::GetMsg()
{
	if(!_recv)
		return _msg;
	return NULL;
}
